// src/store/sagas/auth.saga.ts
import axios from 'axios'
import { put, takeEvery } from 'redux-saga/effects'
import { API } from '../../config'
import { SIGNIN, SigninAction, signinFail, signinSuccess, SIGNUP, SignupAction, signupFail, signupSuccess } from '../actions/auth.action'

function * handleSignup (action: SignupAction) {
    try {
        let response = yield axios.post(`${API}/signup`, action.payload)
        // 注册成功 使用 signupSuccess 方法返回执行注册成功的 dispatch 方法的参数
        yield put(signupSuccess())
    } catch (error) {
        // 注册失败 使用 signupFail 方法接受错误信息并返回注册失败的 dispatch 方法的参数
        yield put(signupFail(error.response.data.error))
    }
}

function * handleSignin (action: SigninAction) {
    try {
        let response = yield axios.post(`${API}/signin`, action.payload)
        localStorage.setItem('jwt', JSON.stringify(response.data))
        yield put(signinSuccess())
    } catch (error) {
        yield put(signinFail(error.response.data.error))
    }
}
export default function * authSaga() {
    // 注册
    yield takeEvery(SIGNUP, handleSignup)
    // 登录
    yield takeEvery(SIGNIN, handleSignin)
}